package fit.deni.pages;

import java.util.Collection;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;

import fit.deni.beans.Klub;
import fit.deni.beans.Zaposleni;
import fit.deni.hibernate.interfaces.LogService;
import fit.deni.hibernate.interfaces.ZaposleniService;
import fit.deni.utils.Utils;

@Import(stylesheet = {"context:layout/css/layout.css", "context:layout/css/tapestry-override.css"})
public class Login {

	@Property
	private String username, password;

	@SessionState
	private Zaposleni korisnik;
	private Zaposleni temp;
	
	@Inject
	private ZaposleniService zaposleniService;
	@Inject
	private LogService logService;
	
	@Component
	private Form loginForm;

	private void onValidateFromLoginForm() {
		temp = zaposleniService.getUserByUsername(username);
		if (temp==null) {
			loginForm.recordError("Korisnik " + username + " ne postoji");
		}
		int passHash = Utils.getHashOf(password);
		if (passHash != temp.getPasswordHash()) {
			loginForm.recordError("Pogresna sifra, pokusajte ponovo");
		}
	}
	
	private Object onSubmitFromLoginForm() {
		if(loginForm.isValid()) {
			korisnik = temp;
			logService.addLog(Utils.createLog("User " + korisnik.getId() + ": " + korisnik.getUsername() + " logged in"));
			return Index.class;
		}
		return null;
	}
	
	public boolean adminNotExist() {
		Collection<Zaposleni> admins = zaposleniService.getAdminitrators();
		if (admins == null || admins.size()<1) return true;
		else return false;
	}
	
	@Property
	private Zaposleni administrator;
	@Property
	private String registerPassword, passwordAgain;
	@Property
	private Klub selectedClub;
	
	@Component
	private BeanEditForm registerForm;
	
	private void onValidateFromRegisterForm() {
		if(!registerPassword.equals(passwordAgain)) {
			registerForm.recordError("Lozinke se ne poklapaju, pokusajte ponovo");
		}
	}
	
	private Object onSubmitFromRegisterForm() {
		if(registerForm.isValid()){
			administrator.setRole(Zaposleni.ADMINISTRATOR);
			administrator.setPasswordHash(Utils.getHashOf(passwordAgain));
			zaposleniService.addUser(administrator);
			administrator = new Zaposleni();
		}
		return this;
	}
	
}
